#-*- coding:utf-8 -*-
import http.server,json
import shelve
import datetime,time

class RequestHandler(http.server.BaseHTTPRequestHandler):
	charset='utf-8'
	#处理一个请求
	def do_HEAD(self):
		self.send_response(200)
		self.send_header("Content-Type","json")
		self.send_header("Access-Control-Allow-Origin","*")
		self.end_headers()

	def do_GET(self):
		# print('GET3==>',self.path)
		self.do_HEAD()
		value=[]
		with shelve.open('deviceinfo/device') as db:
			for k,v in db.items():
				value.append(v)
		value=json.dumps(value)
		content = b''.join(self.make_bytes(chunk) for chunk in value)
		# print(content)
		self.wfile.write(content)

	def do_POST(self):
		# print('POST3==>',self.path)
		self.do_HEAD()
		post_data=eval(self.rfile.read1().decode())
		# print('post_data==>',post_data)
		value=self.query_trail(post_data)
		value=json.dumps(value)
		content = b''.join(self.make_bytes(chunk) for chunk in value)
		self.wfile.write(content)
		# print(content)

	def query_trail(self,data):
		device_id=data['device_id']
		s_time=time.mktime(time.strptime(data['s_time'],'%Y-%m-%d %H:%M:%S'))
		e_time=time.mktime(time.strptime(data['e_time'],'%Y-%m-%d %H:%M:%S'))
		trail=[]
		with shelve.open('deviceinfo/'+device_id) as db:
			for k,v in db.items():
				# print(k,v)
				if k!='id':
					dev_upload=v.get('dev_upload')
					if dev_upload!=None and len(dev_upload)==19:
						dev_upload=time.mktime(time.strptime(dev_upload,'%Y-%m-%d %H:%M:%S'))
						if dev_upload>s_time and dev_upload<e_time:
							trail.append(v)
		return trail

	def make_bytes(self, value):
		# 借用django的httpresopnse
		"""Turn a value into a bytestring encoded in the output charset."""
		# Per PEP 3333, this response body must be bytes. To avoid returning
		# an instance of a subclass, this function returns `bytes(value)`.
		# This doesn't make a copy when `value` already contains bytes.

		# Handle string types -- we can't rely on force_bytes here because:
		# - Python attempts str conversion first
		# - when self._charset != 'utf-8' it re-encodes the content
		if isinstance(value, (bytes, memoryview)):
			return bytes(value)
		if isinstance(value, str):
			return bytes(value.encode(self.charset))
		# Handle non-string types.
		return str(value).encode(self.charset)



if __name__ == '__main__':
	serverAddress = ('', 8898)
	server = http.server.ThreadingHTTPServer(serverAddress, RequestHandler)
	server.serve_forever()
